package com.nbjtjc.safe.service.emg;

import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.emg.EmgGroupMapper;
import com.nbjtjc.safe.mapper.emg.EmgGroupMemberMapper;
import com.nbjtjc.safe.model.emg.EmgGroup;
import com.nbjtjc.safe.model.emg.EmgGroupMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmgGroupMemberService {
    @Autowired
    private EmgGroupMemberMapper emgGroupMemberMapper;
    @Autowired
    private EmgGroupMapper emgGroupMapper;

    @Transactional(rollbackFor = {Throwable.class})
    public Result delete(EmgGroupMember emgGroupMember) throws Exception {
        Result result = new Result();
        if (emgGroupMember == null || emgGroupMember.getId() == null || emgGroupMember.getGroupId() == null) {
            result.setFalse("关键字段不能为空");
            return result;
        }
        int res = emgGroupMemberMapper.deleteByPrimaryKey(emgGroupMember.getId());
        if (res == 0) {
            result.setFalse("删除队员失败");
            return result;
        }
        EmgGroup emgGroup = emgGroupMapper.selectByPrimaryKey(emgGroupMember.getGroupId());
        if (emgGroup == null) {
            result.setFalse("删除失败");
            throw new Exception("删除失败");
        }
        emgGroup.setMemberCount(emgGroup.getMemberCount() - 1);
        emgGroupMapper.updateByPrimaryKeySelective(emgGroup);
        return result;
    }

    @Transactional(rollbackFor = {Throwable.class})
    public Result add(EmgGroupMember emgGroupMember) {
        Result result = new Result();
        if (emgGroupMember == null || emgGroupMember.getGroupId() == null) {
            result.setFalse("groupId 不能为空");
        }

        if (emgGroupMember.getId() != null) {
            emgGroupMemberMapper.updateByPrimaryKeySelective(emgGroupMember);
        } else {
            int res = emgGroupMemberMapper.insertSelective(emgGroupMember);
            if (res == 0) {
                result.setFalse("添加队员失败");
                return result;
            }
            EmgGroup emgGroup = emgGroupMapper.selectByPrimaryKey(emgGroupMember.getGroupId());
            emgGroup.setMemberCount(emgGroup.getMemberCount() + 1);
            emgGroupMapper.updateByPrimaryKeySelective(emgGroup);
        }
        result.setData(emgGroupMember);
        return result;
    }
}
